<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { addFinanceRecordAPI } from '@/pagesOrgan/services/finance'
import type { FinanceRecord } from '@/types/finance'
import UniPopup from '@dcloudio/uni-ui/lib/uni-popup/uni-popup.vue'

const recordType = ref('2')
// 页面加载时初始化数据
onLoad(async (options) => {
  recordType.value = options?.type || '2'
})

// 表单数据
const formData = ref<FinanceRecord>({
  category: '',
  amount: 0,
  paymentMethod: '',
  expenseTime: new Date().toISOString().split('T')[0],
  expenseType: recordType.value,
  remark: '',
})

// 收入分类选项
const incomeCategories = ref(['学费', '服务费', '教材费', '其他收入'])

// 支出分类选项
const expenseCategories = ref(['房租', '工资', '教材', '水电费', '营销费用', '其他支出'])

// 支付方式选项
const paymentMethods = ['现金', '微信', '支付宝', '银行卡']

// 页面标题
const pageTitle = computed(() => {
  return formData.value.expenseType === '2' ? '添加收入' : '添加支出'
})

// 当前可用的分类选项
const availableCategories = computed(() => {
  return formData.value.expenseType === '2' ? incomeCategories.value : expenseCategories.value
})

// 自定义分类相关状态
const customCategoryPopup = ref<InstanceType<typeof UniPopup> | null>(null)
const customCategoryName = ref('')
const customCategoryInputError = ref('')

// 添加自定义分类
const addCustomCategory = () => {
  // 重置错误提示
  customCategoryInputError.value = ''

  // 验证输入
  if (!customCategoryName.value.trim()) {
    customCategoryInputError.value = '分类名称不能为空'
    return
  }

  if (customCategoryName.value.length > 10) {
    customCategoryInputError.value = '分类名称不能超过10个字符'
    return
  }

  if (availableCategories.value.includes(customCategoryName.value)) {
    customCategoryInputError.value = '该分类已存在'
    return
  }

  // 添加到对应分类列表
  if (formData.value.expenseType === '2') {
    incomeCategories.value.push(customCategoryName.value)
  } else {
    expenseCategories.value.push(customCategoryName.value)
  }

  // 自动选择新添加的分类
  formData.value.category = customCategoryName.value

  // 重置并关闭对话框
  customCategoryName.value = ''
  customCategoryPopup.value?.close()
  uni.showToast({ title: '分类添加成功', icon: 'success' })
}

// 打开自定义分类对话框
const openCustomCategoryDialog = () => {
  console.log('打开自定义分类对话框')
  // 重置状态
  customCategoryName.value = ''
  customCategoryInputError.value = ''
  customCategoryPopup.value?.open()
}

// 关闭自定义分类对话框
const closeCustomCategoryDialog = () => {
  customCategoryPopup.value?.close()
  // 重置状态
  setTimeout(() => {
    customCategoryName.value = ''
    customCategoryInputError.value = ''
  }, 300)
}

// 分类选择改变
const onCategoryChange = (e: any) => {
  formData.value.category = availableCategories.value[e.detail.value]
}

// 支付方式选择改变
const onPaymentMethodChange = (e: any) => {
  formData.value.paymentMethod = paymentMethods[e.detail.value]
}

// 日期选择改变
const onDateChange = (e: any) => {
  formData.value.expenseTime = e.detail.value
}

// 提交表单
const submitForm = async () => {
  // 表单验证
  if (!formData.value.category) {
    return uni.showToast({ title: '请选择分类', icon: 'none' })
  }

  if (!formData.value.amount || formData.value.amount <= 0) {
    return uni.showToast({ title: '请输入有效金额', icon: 'none' })
  }

  if (!formData.value.paymentMethod) {
    return uni.showToast({ title: '请选择支付方式', icon: 'none' })
  }

  try {
    await addFinanceRecordAPI(formData.value)
    uni.showToast({ title: '添加成功', icon: 'success' })

    // 返回上一页
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  } catch (error) {
    console.error('提交表单失败:', error)
    uni.showToast({ title: '操作失败', icon: 'error' })
  }
}

// 切换记录类型
const switchRecordType = (type: string) => {
  formData.value.expenseType = type
  formData.value.category = '' // 重置分类
}
</script>

<template>
  <view class="page-container">
    <!-- 页面标题栏 -->
    <view class="header-bar">
      <text class="header-title">{{ pageTitle }}</text>
    </view>

    <view class="form-container">
      <!-- 记录类型选择 -->
      <view class="type-selector">
        <view
          class="type-item"
          :class="{ active: formData.expenseType === '2' }"
          @click="switchRecordType('2')"
        >
          <text>收入</text>
        </view>
        <view
          class="type-item"
          :class="{ active: formData.expenseType === '1' }"
          @click="switchRecordType('1')"
        >
          <text>支出</text>
        </view>
      </view>

      <!-- 表单 -->
      <view class="form">
        <!-- 分类 -->
        <view class="form-item">
          <text class="form-label">分类</text>
          <view class="category-selector">
            <picker :range="availableCategories" @change="onCategoryChange" class="form-picker">
              <view class="picker-display">
                {{ formData.category || '请选择分类' }}
                <uni-icons type="right" size="16" color="#ccc"></uni-icons>
              </view>
            </picker>
            <view class="add-category-btn" @click="openCustomCategoryDialog">
              <uni-icons type="plus" size="16" color="#409eff"></uni-icons>
              <text>添加分类</text>
            </view>
          </view>
        </view>

        <!-- 金额 -->
        <view class="form-item">
          <text class="form-label">金额</text>
          <input
            class="form-input"
            v-model.number="formData.amount"
            type="digit"
            placeholder="请输入金额"
          />
        </view>

        <!-- 支付方式 -->
        <view class="form-item">
          <text class="form-label">支付方式</text>
          <picker :range="paymentMethods" @change="onPaymentMethodChange" class="form-picker">
            <view class="picker-display">
              {{ formData.paymentMethod || '请选择支付方式' }}
              <uni-icons type="right" size="16" color="#ccc"></uni-icons>
            </view>
          </picker>
        </view>

        <!-- 日期 -->
        <view class="form-item">
          <text class="form-label">日期</text>
          <picker
            mode="date"
            start="2000-01-01"
            end="2030-12-31"
            @change="onDateChange"
            class="form-picker"
          >
            <view class="picker-display">
              {{ formData.expenseTime }}
              <uni-icons type="right" size="16" color="#ccc"></uni-icons>
            </view>
          </picker>
        </view>

        <!-- 备注 -->
        <view class="form-item">
          <text class="form-label">备注</text>
          <textarea
            class="form-textarea"
            v-model="formData.remark"
            placeholder="请输入备注信息"
            rows="3"
          ></textarea>
        </view>
      </view>

      <!-- 提交按钮 -->
      <view class="submit-btn" @click="submitForm">
        <text>{{ pageTitle }}</text>
      </view>
    </view>

    <!-- 自定义分类对话框 -->
    <uni-popup
      mode="center"
      ref="customCategoryPopup"
      type="center"
      :mask-click="false"
      :safe-area="true"
    >
      <view class="custom-category-dialog">
        <view class="dialog-title">添加自定义分类</view>
        <input
          v-model="customCategoryName"
          class="dialog-input"
          placeholder="请输入分类名称"
          @input="customCategoryInputError = ''"
        />
        <text v-if="customCategoryInputError" class="error-message">{{
          customCategoryInputError
        }}</text>
        <view class="dialog-buttons">
          <view class="dialog-btn cancel-btn" @click="closeCustomCategoryDialog">
            <text>取消</text>
          </view>
          <view class="dialog-btn confirm-btn" @click="addCustomCategory">
            <text>确定</text>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<style lang="scss">
.page-container {
  height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.header-bar {
  height: 90rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  .header-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }
}

.form-container {
  flex: 1;
  background-color: #fff;
  padding: 30rpx 20rpx;
  box-sizing: border-box;
  margin-top: 10rpx;
}

.type-selector {
  display: flex;
  margin-bottom: 30rpx;
  .type-item {
    flex: 1;
    text-align: center;
    padding: 20rpx;
    border-radius: 10rpx;
    background-color: #f5f7fa;
    margin: 0 10rpx;
    font-size: 32rpx;
    color: #666;
    transition: all 0.3s ease;
    &.active {
      background-color: #409eff;
      color: #fff;
      transform: translateY(-2rpx);
      box-shadow: 0 4rpx 12rpx rgba(64, 158, 255, 0.3);
    }
  }
}

.form {
  margin-bottom: 40rpx;
}

.form-item {
  margin-bottom: 30rpx;
  .form-label {
    display: block;
    font-size: 28rpx;
    color: #333;
    margin-bottom: 10rpx;
    font-weight: 500;
  }
  .category-selector {
    position: relative;
  }
  .form-picker {
    .picker-display {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 24rpx;
      background-color: #f5f7fa;
      border-radius: 10rpx;
      font-size: 28rpx;
      color: #666;
      border: 1rpx solid #e4e7ed;
      transition: all 0.3s ease;
      &:active {
        background-color: #e6f7ff;
        border-color: #409eff;
      }
    }
  }
  .add-category-btn {
    position: absolute;
    right: 20rpx;
    top: 50%;
    transform: translateY(-50%);
    display: flex;
    align-items: center;
    font-size: 26rpx;
    color: #409eff;
    z-index: 10;
    text {
      margin-left: 6rpx;
    }
  }
  .form-input {
    width: 100%;
    padding: 24rpx;
    background-color: #f5f7fa;
    border-radius: 10rpx;
    font-size: 28rpx;
    border: 1rpx solid #e4e7ed;
    box-sizing: border-box;
    transition: all 0.3s ease;
    /* 添加这行确保输入框内容居中显示 */
    display: flex;
    align-items: center;
    /* 增加高度确保内容有足够空间显示 */
    min-height: 90rpx;
    &:focus {
      border-color: #409eff;
      background-color: #fff;
    }
  }
  .form-textarea {
    width: 100%;
    padding: 24rpx;
    background-color: #f5f7fa;
    border-radius: 10rpx;
    font-size: 28rpx;
    box-sizing: border-box;
    border: 1rpx solid #e4e7ed;
    transition: all 0.3s ease;
    &:focus {
      border-color: #409eff;
      background-color: #fff;
    }
  }
}

.submit-btn {
  width: 100%;
  padding: 28rpx;
  background-color: #409eff;
  color: #fff;
  text-align: center;
  border-radius: 10rpx;
  font-size: 32rpx;
  font-weight: bold;
  transition: all 0.3s ease;
  margin-top: 20rpx;
  &:active {
    background-color: #3a8ee6;
    transform: scale(0.98);
  }
}

/* 自定义分类对话框样式 */
.custom-category-dialog {
  width: 600rpx;
  max-width: 90%;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-sizing: border-box;
  z-index: 10000;
  // 添加阴影效果增强视觉层次感
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.15);

  .dialog-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    text-align: center;
    margin-bottom: 30rpx;
  }

  .dialog-input {
    width: 100%;
    padding: 24rpx;
    border: 1rpx solid #e4e7ed;
    border-radius: 8rpx;
    font-size: 28rpx;
    box-sizing: border-box;
    margin-bottom: 10rpx;
    // 增强输入框的可点击区域
    min-height: 80rpx;
    display: flex;
    align-items: center;
  }

  .error-message {
    display: block;
    color: #f56c6c;
    font-size: 24rpx;
    margin-bottom: 20rpx;
    padding-left: 10rpx;
  }

  .dialog-buttons {
    display: flex;
    .dialog-btn {
      flex: 1;
      text-align: center;
      padding: 20rpx;
      font-size: 30rpx;
      border-radius: 8rpx;
      margin: 0 10rpx;
    }
    .cancel-btn {
      color: #666;
      background-color: #f5f7fa;
    }
    .confirm-btn {
      color: #fff;
      background-color: #409eff;
    }
  }
}

/* 响应式适配 */
@media screen and (max-width: 320px) {
  .form-container {
    padding: 20rpx 15rpx;
  }
  .type-item {
    padding: 15rpx 10rpx;
    font-size: 28rpx;
  }
  .form-item {
    margin-bottom: 25rpx;
  }
  .form-input,
  .form-picker .picker-display,
  .form-textarea {
    padding: 20rpx;
    font-size: 26rpx;
  }
  .submit-btn {
    padding: 24rpx;
    font-size: 30rpx;
  }
  .custom-category-dialog {
    width: 90%;
    padding: 20rpx;
  }
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.form-item {
  animation: fadeIn 0.3s ease-out;
}

.form-item:nth-child(2) {
  animation-delay: 0.1s;
}

.form-item:nth-child(3) {
  animation-delay: 0.2s;
}

.form-item:nth-child(4) {
  animation-delay: 0.3s;
}

.form-item:nth-child(5) {
  animation-delay: 0.4s;
}
@media screen and (max-width: 768px) {
  .form-container {
    /* 确保表单内容不会被键盘完全遮挡 */
    padding-bottom: 100rpx;
  }
}
</style>
